package com.huawei.boss.resources;

import java.util.List;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;

import com.ibatis.sqlmap.client.SqlMapClient;

public class DatabaseResourceFactoryBean implements InitializingBean, FactoryBean {
    private static final String DEFAULT_CHARSET = "UTF-8";
    private SqlMapClient sqlLoaderClient;
    private String location;
    private Resource[] resources;

    public void setSqlLoaderClient(SqlMapClient sqlLoaderClient) {
        this.sqlLoaderClient = sqlLoaderClient;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        List allres = sqlLoaderClient.queryForList(location);
        final int size = allres.size();
        this.resources = new Resource[size];
        for (int i = 0; i < size; i++) {
            String s = (String) allres.get(i);
            this.resources[i] = new ByteArrayResource(s.getBytes(DEFAULT_CHARSET));
        }
    }

    @Override
    public Object getObject() throws Exception {
        return this.resources;
    }

    @Override
    public Class getObjectType() {
        return Resource[].class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}